package com.atguigu.flink0922.chapter11;

import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/12 8:45
 */
public class Flink10_SQL_Window_Over {
    
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        tEnv.executeSql("create table sensor(" +
                            "id string," +
                            "ts bigint," +
                            "vc int, " +
                            "t as to_timestamp(from_unixtime(ts/1000,'yyyy-MM-dd HH:mm:ss'))," +
                            "watermark for t as t - interval '5' second)" +
                            "with("
                            + "'connector' = 'filesystem',"
                            + "'path' = 'input/sensor.txt',"
                            + "'format' = 'csv'"
                            + ")");
        
        
    
        /*tEnv
            .sqlQuery("select " +
                          " id, " +
                          " ts, " +
                          " sum(vc) over(partition by id order by t)" +
                          "from sensor ")
            .execute()
            .print();*/
    
        tEnv
            .sqlQuery("select " +
                          " id, " +
                          " ts, " +
                          " sum(vc) over w, " +
                          " max(vc) over w, " +
                          " min(vc) over w " +
//                          " sum(vc) over(partition by id order by t rows between 2 preceding and current row)" +
                          "from sensor " +
//                          "window w as (partition by id order by t rows between unbounded preceding and current row)")
                          "window w as (partition by id order by t range between interval '1' second preceding and current row)")
            .execute()
            .print();
    }
}
